<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\User;
use App\Server\JwtServer;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
  // 登录
  public function login(Request $request)
  {
    // 设置验证规则
    $rule = [
      'username' => 'required',
      'password' => 'required|min:6|max:15'
    ];
    // 设置验证信息
    $message = [
      'username.required' => '用户名不能为空',
      'password.required' => '密码不能为空',
      'password.min' => '密码长度在 6 到 15 个字符',
      'password.max' => '密码长度在 6 到 15 个字符'
    ];
    $validator = Validator::make($request->all(), $rule, $message);
    if ($validator->fails()) {
      foreach ($validator->getMessageBag()->toArray() as  $v) {
        $msg = $v[0];
      }
      return ['status' => 400, 'msg' => $msg];
    }
    // 获取传递过来的参数
    $username = $request->get('username');
    $password = $request->get('password');
    // 根据用户名获取数据库信息
    $userInfo = User::where('name', $username)->first();
    // 判断用户是否存在
    if (!$userInfo) return ['status' => 400, 'msg' => '用户不存在！',];
    // 判断密码是否正确
    if ($password !== $userInfo->password) return ['status' => 400, 'msg' => '密码错误！',];
    $request->session()->put('userInfo', ['id' => $userInfo->id, 'username' => $username]);
    // 生成token
    $token = JwtServer::createToken($userInfo->id);
    // 登录成功
    return ['status' => 200, 'msg' => '登录成功！', 'token' => $token, 'userInfo' => [
      'id' => $userInfo->id,
      'username' => $userInfo->name
    ]];
  }

  // 注册
  public function registe(Request $request)
  {
    // 设置验证规则
    $rule = [
      'username' => 'required',
      'password' => 'required|min:6|max:15',
      'email' => 'required|email'
    ];
    // 设置验证信息
    $message = [
      'username.required' => '用户名不能为空',
      'password.required' => '密码不能为空',
      'password.min' => '密码长度在 6 到 15 个字符',
      'password.max' => '密码长度在 6 到 15 个字符',
      'email.required' => '邮箱不能为空',
      'email.email' => '邮箱地址格式错误'
    ];
    $validator = Validator::make($request->all(), $rule, $message);
    if ($validator->fails()) {
      foreach ($validator->getMessageBag()->toArray() as  $v) {
        $msg = $v[0];
      }
      return ['status' => 400, 'msg' => $msg];
    }
    $username = $request->get('username');
    $password = $request->get('password');
    $email = $request->get('email');
    // 获取根据参数获取数据库信息
    $userInfo = User::where('email', $email)->first();
    if ($userInfo) return ['status' => 400, 'msg' => '邮箱地址已存在！'];
    // 添加用户
    $user = new User();
    $user->name = $username;
    $user->password = $password;
    $user->email = $email;
    $result = $user->save();
    // 注册失败
    if (!$result) return ['status' => 200, 'msg' => '注册失败！'];
    // 注册成功
    return ['status' => 200, 'msg' => '注册成功！'];
  }
}
